package com.j3.string;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class J3Encode {

	public static String encode(String sourceString) {
		StringBuffer buffer = new StringBuffer();
		int len = sourceString.length();
		for (int i = 0; i < len; i++) {
			char chr = sourceString.charAt(i);
			String string = String.valueOf(chr);
			if (isChinese(string)) {
				int chi = (int) chr;
				buffer.append('_');
				buffer.append(Integer.toHexString(chi));
			} else {
				buffer.append('_');
				buffer.append(chr);
			}
		}
		return buffer.toString();
	}

	public static String decode(String sourceString) {
		StringBuffer buffer = new StringBuffer();
		String[] matrix = sourceString.split("\\_");
		for (int i = 0; i < matrix.length; i++) {
			String temp = matrix[i];
			if (temp == null || "".equals(temp)) {
				continue;
			}
			if (isNumber(temp)) {
				int chi = Integer.parseInt(temp, 16);
				buffer.append((char) chi);
			} else {
				buffer.append(temp);
			}
		}
		return buffer.toString();
	}

	public static final String REG_NUMBER = "[0-9a-f]{4}";
	public static final String REG_CHINESE = "[\\u4e00-\\u9fa5]+";

	public static boolean isChinese(String txt) {
		Pattern pattern = Pattern.compile(REG_CHINESE);
		Matcher matcher = pattern.matcher(txt);
		return matcher.matches();
	}

	public static boolean isNumber(String txt) {
		Pattern pattern = Pattern.compile(REG_NUMBER);
		Matcher matcher = pattern.matcher(txt);
		return matcher.matches();
	}
}
